package com.tools.xxf.updatelib.apkinfo;

import android.util.Log;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * TODO
 *
 * @author XXF
 *         Create Time : 2017/11/6 15:09
 */
public class ApkData {
    private static final long DEFAULT_TIMEOUT = 3000;
    private Retrofit.Builder mRetrofitBuilder;
    private static Retrofit retrofit;

    /**
     * 完美的单例模式
     * 线程安全的懒汉模式
     */
    public static ApkData getInstance() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static final ApkData INSTANCE = new ApkData();
    }

    private ApkData() {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        okHttpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        retrofit = new Retrofit.Builder().client(okHttpClientBuilder.build()).addConverterFactory
                (GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).baseUrl
                        ("http://171.221.202.190:1010/").build();
    }

    /**
     * xxf
     * 新增apk Token获取,额Apk最新信息查询类
     *
     * @param subscriber 由调用者传过来的观察者对象
     */
    @SuppressWarnings("unchecked")
    public void getToken(Subscriber<ApkToken> subscriber, String account, String
            password) {
        GitHubService service = retrofit.create(GitHubService.class);
        Observable<ApkToken> observable = service.getToken(account, password);
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public void getAPKinfo(
            Subscriber<ApkInFoBean> subscriber,
            String packageName,
            String version,
            String token) {
        Log.d("123", packageName + ",version=" + version + ",token=" + token);
        GitHubService service = retrofit.create(GitHubService.class);
        Observable<ApkInFoBean> observable = service.getApkInfo(packageName, version, token);
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

    }
}
